package jupiter.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.danga.MemCached.*;
public class MemCache {

	// create a static client as most installs only need
	// a single instance
	static Logger logger = LoggerFactory.getLogger(MemCache.class);
	protected static MemCachedClient mcc = new MemCachedClient();

	// set up connection pool once at class load
	static {

		// server list and weights
		String[] servers =
			{
			  "localhost:11211"
			};

		Integer[] weights = { 1 };

		// grab an instance of our connection pool
		SockIOPool pool = SockIOPool.getInstance();

		// set the servers and the weights
		pool.setServers( servers );
		pool.setWeights( weights );

		// set some basic pool settings
		// 5 initial, 5 min, and 250 max conns
		// and set the max idle time for a conn
		// to 6 hours
		pool.setInitConn( 5 );
		pool.setMinConn( 5 );
		pool.setMaxConn( 250 );
		pool.setMaxIdle( 1000 * 60 * 60 * 6 );

		// set the sleep for the maint thread
		// it will wake up every x seconds and
		// maintain the pool size
		pool.setMaintSleep( 30 );

		// set some TCP settings
		// disable nagle
		// set the read timeout to 3 secs
		// and don't set a connect timeout
		pool.setNagle( false );
		pool.setSocketTO( 3000 );
		pool.setSocketConnectTO( 0 );

		// initialize the connection pool
		pool.initialize();


		// lets set some compression on for the client
		// compress anything larger than 64k
		mcc.setCompressEnable( true );
		mcc.setCompressThreshold( 64 * 1024 );
	}

	/**
	 * Returns true if domain exists in the database, false otherwise.
	 * Checks cache for domain.  If it exists, returns true.
	 * Otherwise, check the database.  If it exists, set the cache.
	 * Otherwise returns false.
	 * @param domain_name
	 * @return
	 */
	public static boolean get_domain(String domain_name){
		Object domain_found = null;
		domain_found = mcc.get(domain_name);
		if(domain_found != null){
			return true;
		} else {
			Connection conn = null;
		    Statement stmt = null;
		    ResultSet rs = null;
			try{			
				// am i banned?
				// perform asynchronous insert, don't wait for result
				conn = DBConnection.ds.getConnection();
				stmt = conn.createStatement();
				rs = stmt.executeQuery("SELECT d.id FROM domains d WHERE d.name='"+domain_name+"'");
				String domain_id = null;
				while (rs.next()) {
		            domain_id = rs.getString("d.id");
		        }
		        rs.close();
		        stmt.close();
		        conn.close();
				if(domain_id != null) {
			        mcc.set( domain_name, true );
			        return true;
				}
				return false;
			}catch(SQLException e){
				try{
			        rs.close();
			        stmt.close();
			        conn.close();
		        } catch(SQLException close_e){
					logger.error("SQLException: ERROR in closing connections", close_e);
		        }
				logger.error("SQLException", e);
			}
			return false;
		}
	}
}